package com.lizemin.controller;

import cn.hutool.core.util.StrUtil;
import com.lizemin.constant.Constants;
import com.lizemin.entity.User;
import com.lizemin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author lzm
 * @date 2025/4/6 11:33
 * @description
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    HttpServletRequest request;

    /**
     * 登录接口
     * @param username 用户名
     * @param password  密码
     */
    @GetMapping("/login")
    public String login(String username, String password) {
        if (StrUtil.hasBlank(username, password)) {
            throw new RuntimeException("用户名或密码不能为空");
        }
        log.info("用户名：{}，密码：{}", username, password);
        HttpSession session = request.getSession();
        String oldSessionId = session.getId();
        log.info("原始的sessionId为：{}", oldSessionId);
        User user = userService.findUserByUsernameAndPassword(username, password);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在或密码错误");
        }
        // 认证成功后，修改sessionId, 防止会话固定攻击
        String newSessionId = request.changeSessionId();
        log.info("新的sessionId为：{}", newSessionId);
        // 将用户信息存入session中
        session.setAttribute(Constants.LOGIN_STATUS, user);
        return "登录成功";
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout() {
        request.getSession().invalidate();
        return "已退出登录";
    }

}
